<template>
  <view class="page">
    <!-- 使用 z-paging 实现滚动和分页 -->
    <z-paging 
      ref="paging" 
      v-model="whaleList" 
      :fixed="true" 
      safe-area-inset-bottom 
      :default-page-size="20"
      :auto-show-back-to-top="true" 
      :refresher-enabled="true" 
      :loading-more-enabled="true" 
      @query="queryList"
    >
      <!-- 顶部固定区域 - 导航栏 -->

      <!-- 加载动画 -->
      <view v-if="isLoading && whaleList.length === 0" class="loading-container">
        <uv-loading-icon mode="circle" color="#00d4aa" size="40"></uv-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态提示 -->
      <view v-else-if="!isLoading && whaleList.length === 0" class="empty-state">
        <text class="empty-text">暂无数据</text>
      </view>

      <!-- 大额转账列表 -->
      <view v-else class="whale-list">
        <view 
          class="whale-item" 
          v-for="(item, idx) in whaleList" 
          :key="item.id || idx"
        >
          <!-- 主要内容区域 -->
          <view class="content-wrapper">
            <!-- 顶部：重要性警报标记和时间 -->
            <view class="top-row">
              <view class="importance-badges">
                <text 
                  v-for="(alert, alertIdx) in Array(item.importance).fill(0)" 
                  :key="alertIdx"
                  class="alert-icon"
                >🚨</text>
              </view>
              
              <!-- 时间显示 - 智能格式化 -->
              <view v-if="item.hasValidTime" class="time-wrapper">
                <text class="display-time">{{ item.displayTime }}</text>
              </view>
            </view>
            
            <!-- 内容行：币种图标、金额信息 -->
            <view class="content-row">
              <!-- 左侧：币种图标 -->
              <view class="coin-icon-wrapper">
                <image 
                  class="coin-icon" 
                  :src="item.logoUrl || getCoinIcon(item.symbol)" 
                  mode="aspectFit"
                />
              </view>

              <!-- 中间：金额和转账信息 -->
              <view class="info-main">
                <!-- 金额行 -->
                <view class="amount-row">
                  <text class="amount">{{ item.assetQuantity }}</text>
                  <text class="symbol">#{{ item.symbol }}</text>
                  <text class="usd-value">({{ item.amountUsd }} USD)</text>
                </view>

                <!-- 转账路径 - 始终显示，没有数据时显示"未知转未知" -->
                <view class="transfer-path">
                  <text class="transfer-text">
                    从<text class="wallet-link">{{ item.fromWallet ? (item.fromWallet.startsWith('#') ? item.fromWallet : '#' + item.fromWallet) : '未知' }}</text> 钱包转移到 <text class="wallet-link">{{ item.toWallet ? (item.toWallet.startsWith('#') ? item.toWallet : '#' + item.toWallet) : '未知' }}</text> 钱包
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>  
    </z-paging>
  </view>
</template>

<script>
import { getWhaleTransferPage } from '@/api/data'
import { formatSmartTime } from '@/utils/time-formatter'

export default {
  data() {
    const sys = uni.getSystemInfoSync()
    const statusBarPx = sys.statusBarHeight || 0
    
    return {
      statusBarPx,
      whaleList: [], // z-paging 数据列表
      isLoading: false, // 加载状态
      isFirstLoad: true, // 标记是否首次加载
    }
  },
  
  onShow() {
    // 首次加载时，z-paging 会自动调用 queryList，不需要手动 reload
    if (this.isFirstLoad) {
      this.isFirstLoad = false
      return
    }
    
    // 确保 paging 组件已经初始化，刷新数据
    this.$nextTick(() => {
      if (this.$refs.paging) {
        this.$refs.paging.reload(true)
      }
    })
  },
  
  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },
    
    /**
     * z-paging 查询数据方法（服务端分页）
     * @param {Number} pageNo - 页码
     * @param {Number} pageSize - 每页数量
     */
    async queryList(pageNo, pageSize) {
      try {
        console.log('请求大额转账数据:', { pageNo, pageSize })
        
        this.isLoading = true
        
        // 调用分页接口
        const response = await getWhaleTransferPage({
          pageNo: pageNo,
          pageSize: pageSize
        })
        
        console.log('大额转账响应:', response)
        
        // 获取分页数据
        const whaleData = response.data || {}
        const records = whaleData.records || []
        
        console.log('返回数据条数:', records.length)
        console.log('总记录数:', whaleData.total)
        
        // 调试：打印第一条数据看看格式
        if (records.length > 0) {
          console.log('第一条原始数据示例:', records[0])
        }
        
        // 格式化数据
        const formattedData = records.map((item, index) => {
          // 使用时间格式化工具处理时间
          const blockTime = item.blockTimestamp || item.timestamp
          const smartTime = formatSmartTime(blockTime)
          const hasValidTime = !!smartTime
          
          // 解析美元金额（兼容字符串和数字类型）
          let amountUsdNum = 0
          const amountUsdStr = String(item.amountUsd || '0')
          amountUsdNum = parseFloat(amountUsdStr.replace(/,/g, '')) || 0
          
          // 计算重要性（根据金额大小，决定显示多少个🚨）
          let importance = 3
          if (amountUsdNum >= 100000000) { // 1亿美元以上
            importance = 10
          } else if (amountUsdNum >= 50000000) { // 5000万美元以上
            importance = 7
          } else if (amountUsdNum >= 10000000) { // 1000万美元以上
            importance = 5
          }
          
          // 处理钱包地址信息
          let fromWallet = item.from ? String(item.from).trim() : null
          let toWallet = item.to ? String(item.to).trim() : null

          // 如果钱包地址包含 "unknown"（不区分大小写），格式化为 "未知"
          if (fromWallet && fromWallet.toLowerCase().includes('unknown')) {
            fromWallet = null // 设为 null，让模板显示"未知"
          }
          if (toWallet && toWallet.toLowerCase().includes('unknown')) {
            toWallet = null // 设为 null，让模板显示"未知"
          }
          
          // 区块链名称
          const blockchainName = item.blockchainName || ''
          
          return {
            id: item.id || `whale-${Date.now()}-${index}`,
            symbol: item.assetSymbol || 'USDT',
            assetQuantity: item.assetQuantity || '0',
            amountUsd: amountUsdStr,
            logoUrl: item.logoUrl || '',
            blockchainName: blockchainName,
            displayTime: smartTime, // 智能格式化的时间
            blockTimestamp: item.blockTimestamp,
            importance: importance,
            hasValidTime: hasValidTime,
            fromWallet: fromWallet || null,
            toWallet: toWallet || null,
          }
        })
        
        this.isLoading = false
        
        // 完成加载
        this.$refs.paging.complete(formattedData)
      } catch (error) {
        console.error('加载大额转账数据失败:', error)
        
        this.isLoading = false
        
        // 加载失败
        this.$refs.paging.complete(false)
        
        uni.showToast({
          title: error.message || '加载失败，请重试',
          icon: 'none',
          duration: 2000,
        })
      }
    },
    
    /**
     * 获取币种图标（备用方案）
     * @param {String} symbol - 币种符号
     * @returns {String} 图标URL
     */
    getCoinIcon(symbol) {
      
      // 默认图标
      return '/static/images/data/coin.png'
    },
  },
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;
  background:#f8f8f8;
}

/* 导航栏 */
.nav-bar {
  position: relative;
  width: 100%;
  background: #ffffff;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 24rpx;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;
  
  &:active {
    opacity: 0.6;
  }
}

.nav-back-text {
  font-size: 28rpx;
  color: #303133;
}

.nav-title {
  position: absolute;
  left: 24rpx;
  font-size: 34rpx;
  font-weight: 700;
  color: #2a2b2f;
}

.nav-right {
  width: 80rpx;
}

/* 加载和空状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #00d4aa;
  font-weight: 500;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #c0c4cc;
}

/* 列表容器 */
.whale-list {
  padding: 24rpx;
}

/* 转账条目 */
.whale-item {
  position: relative;
  margin-bottom: 24rpx;
  padding: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  border: 1px solid #f0f3f8;
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
  }
}

/* 内容区域 */
.content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

/* 顶部行：警报和时间 */
.top-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16rpx;
}

/* 重要性警报标记 */
.importance-badges {
  display: flex;
  gap: 4rpx;
  flex-wrap: wrap;
  align-items: center;
  flex: 1;
  line-height: 1;
}

.alert-icon {
  font-size: 28rpx;
  line-height: 1;
  display: inline-block;
}

/* 内容行：币种图标、金额信息横向排列 */
.content-row {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
}

/* 左侧：币种图标 */
.coin-icon-wrapper {
  flex-shrink: 0;
  width: 64rpx;
  height: 64rpx;
}

.coin-icon {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: #f5f7fa;
}

/* 中间：金额和转账信息 */
.info-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  min-width: 0;
}

/* 金额行 */
.amount-row {
  display: flex;
  align-items: baseline;
  gap: 6rpx;
  flex-wrap: wrap;
}

.amount {
  font-size: 32rpx;
  font-weight: 700;
  color: #303133;
  line-height: 1.4;
}

.symbol {
  font-size: 28rpx;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.usd-value {
  font-size: 24rpx;
  color: #909399;
  line-height: 1.4;
}

/* 转账路径 */
.transfer-path {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  line-height: 1.6;
}

.transfer-text {
  font-size: 26rpx;
  color: #606266;
  line-height: 1.6;
}

.wallet-link {
  font-size: 26rpx;
  color: #00d4aa;
  text-decoration: underline;
  cursor: pointer;
  
  &:active {
    opacity: 0.7;
  }
}

/* 时间显示 */
.time-wrapper {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.display-time {
  font-size: 24rpx;
  color: #606266;
  line-height: 1.4;
  white-space: nowrap;
  text-align: right;
}
</style>

